package com.neusoft.elm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.neusoft.elm.po.Orders;
import com.neusoft.elm.service.OrdersService;
import com.neusoft.elm.service.impl.OrdersServiceImpl;

@WebServlet("/OrderServlet")
public class OrderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        
        PrintWriter out = response.getWriter();
        
        try {
            String action = request.getParameter("action");
            OrdersService ordersService = new OrdersServiceImpl();
            
            if ("create".equals(action)) {
                // 创建订单
                createOrder(request, response, ordersService, out);
            } else if ("pay".equals(action)) {
                // 支付订单
                payOrder(request, response, ordersService, out);
            } else if ("getById".equals(action)) {
                // 根据ID获取订单
                getOrderById(request, response, ordersService, out);
            } else if ("listByUser".equals(action)) {
                // 获取用户订单列表
                getOrdersByUser(request, response, ordersService, out);
            } else {
                out.print("{\"success\":false,\"message\":\"无效的操作类型\"}");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            out.print("{\"success\":false,\"message\":\"操作失败: " + e.getMessage() + "\"}");
        } finally {
            out.close();
        }
    }
    
    private void createOrder(HttpServletRequest request, HttpServletResponse response, 
                            OrdersService ordersService, PrintWriter out) throws Exception {
        String userId = request.getParameter("userId");
        String businessIdStr = request.getParameter("businessId");
        String daIdStr = request.getParameter("daId");
        
        if (userId == null || businessIdStr == null || daIdStr == null) {
            out.print("{\"success\":false,\"message\":\"参数不完整\"}");
            return;
        }
        
        Integer businessId = Integer.valueOf(businessIdStr);
        Integer daId = Integer.valueOf(daIdStr);
        
        int orderId = ordersService.createOrders(userId, businessId, daId);
        
        if (orderId > 0) {
            out.print("{\"success\":true,\"message\":\"订单创建成功\",\"orderId\":" + orderId + "}");
        } else {
            out.print("{\"success\":false,\"message\":\"订单创建失败\"}");
        }
    }
    
    private void payOrder(HttpServletRequest request, HttpServletResponse response, 
                         OrdersService ordersService, PrintWriter out) throws Exception {
        String orderIdStr = request.getParameter("orderId");
        String paymentMethod = request.getParameter("paymentMethod");
        
        if (orderIdStr == null || paymentMethod == null) {
            out.print("{\"success\":false,\"message\":\"参数不完整\"}");
            return;
        }
        
        Integer orderId = Integer.valueOf(orderIdStr);
        
        // 获取订单信息
        Orders order = ordersService.getOrdersById(orderId);
        if (order == null) {
            out.print("{\"success\":false,\"message\":\"订单不存在\"}");
            return;
        }
        
        // 检查订单状态
        if (order.getOrderState() != 0) {
            out.print("{\"success\":false,\"message\":\"订单状态异常，无法支付\"}");
            return;
        }
        
        // 模拟支付过程
        boolean paymentSuccess = simulatePayment(paymentMethod, order.getOrderTotal());
        
        if (paymentSuccess) {
            // 更新订单状态为已支付
            order.setOrderState(1);
            // 这里需要在OrdersService中添加updateOrderState方法
            // 暂时直接返回成功
            out.print("{\"success\":true,\"message\":\"支付成功\",\"orderId\":" + orderId + "}");
        } else {
            out.print("{\"success\":false,\"message\":\"支付失败，请重试\"}");
        }
    }
    
    private void getOrderById(HttpServletRequest request, HttpServletResponse response, 
                             OrdersService ordersService, PrintWriter out) throws Exception {
        String orderIdStr = request.getParameter("orderId");
        
        if (orderIdStr == null) {
            out.print("{\"success\":false,\"message\":\"订单ID不能为空\"}");
            return;
        }
        
        Integer orderId = Integer.valueOf(orderIdStr);
        Orders order = ordersService.getOrdersById(orderId);
        
        if (order != null) {
            Gson gson = new Gson();
            String jsonResult = gson.toJson(order);
            out.print(jsonResult);
        } else {
            out.print("{\"success\":false,\"message\":\"订单不存在\"}");
        }
    }
    
    private void getOrdersByUser(HttpServletRequest request, HttpServletResponse response, 
                                OrdersService ordersService, PrintWriter out) throws Exception {
        String userId = request.getParameter("userId");
        
        if (userId == null) {
            out.print("{\"success\":false,\"message\":\"用户ID不能为空\"}");
            return;
        }
        
        List<Orders> ordersList = ordersService.listOrdersByUserId(userId);
        
        Gson gson = new Gson();
        String jsonResult = gson.toJson(ordersList);
        out.print(jsonResult);
    }
    
    /**
     * 模拟支付过程
     * @param paymentMethod 支付方式
     * @param amount 支付金额
     * @return 支付是否成功
     */
    private boolean simulatePayment(String paymentMethod, Double amount) {
        // 模拟支付过程，这里简单返回true表示支付成功
        // 实际项目中需要调用第三方支付接口
        try {
            // 模拟网络延迟
            Thread.sleep(1000);
            
            // 模拟支付成功率95%
            return Math.random() > 0.05;
        } catch (InterruptedException e) {
            return false;
        }
    }
}